var xmlHttp;
var addwindow = '';
var loadwindow = '';
var savewindow = '';
var exportwindow = '';
var debugwindow = '';

var canvas;

// When adding/modifying tabs, these vars must be updated
var tabCt = 5;
var gameIdx = 1;
var grammarIdx = 3;

///////// PRACTICE /////////

function resetTabs() {
	for (i = 0; i < tabCt; i++) {
		var tab = document.getElementById("Tab" + i);		
		tab.style.zIndex = 0;
		tab.style.borderBottom = "1px solid #484848";
	}
}

function hideGrammar() {
	var grammar = document.getElementById("Grammar");
	grammar.style.visibility = "hidden";
	grammar.style.zIndex = 0;
}

function resetGrammar() {
	var grammar = document.getElementById("Grammar");
	grammar.style.visibility = "visible";
	grammar.style.zIndex = 1;
}

function clickTab(i) {
	resetTabs();
	hideContent();
	resetContent(i);
	var tab = document.getElementById("Tab" + i);
	tab.style.borderBottom = "1px solid #FFF";
	tab.style.zIndex = 2;
}

function hideContent() {
	hideGame();
	hideGrammar();	
	for (i = 0; i < tabCt; i++) {
		var content = document.getElementById("Content" + i);
		content.style.visibility = "hidden";
		content.style.zIndex = 0;
	}
}

function resetContent(i) {
	if ( i == gameIdx ) resetGame();
	if ( i == grammarIdx ) resetGrammar();
	var content = document.getElementById("Content" + i);
	content.style.visibility = "visible";
	content.style.zIndex = 1;
}

function removeAllItems( select ) {
	var options = select.options;
	for ( var i = options.length-1; i >= 0; i-- ) {
		options[i] = null;
	}
}

function removeItems( select ) {
	var options = select.options;
	for ( var i = options.length-1; i >= 0; i-- ) {
		if ( options[i].selected ) {
			options[i] = null;
		}
	}
}

function copyToPickList() {

	var pool = document.practicef.pool;
	var options = pool.options;
	for ( var i=0; i < options.length; i++){
		if (options[i].selected) {
			addItemToPickList( options[i].value );
		}
	}
}

function copyAllToPickList() {

	var pool = document.practicef.pool;
	var options = pool.options;
	for ( var i=0; i < options.length; i++){
			addItemToPickList( options[i].value );
	}
}

function addItemToPickList( value ) {

	var picklist = document.getElementById("picklist");
	var newOpt = new Option(value,value,false,false);
	newOpt.title = value;
	picklist.options[picklist.length] = newOpt;
}

function removeFromPickList() {
	removeItems( document.practicef.picklist );
}

function more() {
	
	removeAllItems(document.practicef.pool);
	
	xmlHttp = getXmlHttpObject();
    var url = "server/language/wordlist.php";
    url = url + "?language=" + document.practicef.language.value;
    url = url + "&wordlist=" + document.practicef.wordlist.value;
    
    post( xmlHttp, url, addToPool );    
}

function addToPool() {

	if (xmlHttp.readyState==4) {
        
        var response = xmlHttp.responseText;
        if ( response == "File does not exist" ) {
        	document.practicef.morebutton.disabled = true;
        } else {
        	var words = xmlHttp.responseText.split(";");
	        var pool = document.practicef.pool;
	        for ( var i = 0; i < words.length; i++ ) {
	        	if ( words[i].length > 0 ) {
	        		var l = pool.options.length;
	        		pool.options[l] = new Option(words[i],words[i]);
	        		pool.options[l].title = words[i];
	        	}
	        }
	        var listid = parseInt( document.practicef.listid.value ) + 1;
	        document.practicef.listid.value = "" + listid;
	    } 
    }
}

function addOwn() {

	var url = "additem.php?language=" + document.getElementById("language").value;
	return openWindow( url, addwindow, "addwindow", "height=300,width=450"); 
}

function loadItems() {

	return openWindow( "loaditems.php", loadwindow, "loadwindow", "height=500,width=300" );	
}

function saveItems() {

	return openWindow( "saveitems.php", savewindow, "savewindow", "height=500,width=300" );
}

function exportItems() {

	return openWindow( "exportitems.php", exportwindow, "exportwindow", "height=600,width=450" ); 
}

function clearItems() {

	var srcLength = document.practicef.picklist.options.length; 
	for(var i = srcLength; i>=0; i--) {
		document.practicef.picklist.options[i]=null;
	}  	
}

function switchLayout() {

	var language = document.cardsf.showcards[1].value;
	if ( language == 'Korean' ) {
		VirtualKeyboard.switchLayout('KR','2 Beolsik');
	} else if ( language == "French" ) {
		VirtualKeyboard.switchLayout('FR','French');
	}
}

///////// UTILITY /////////

function resize(element,width,height) {
	element.style.width = width;
	element.style.height = height;
}

function openWindow(url, newwindow, name, props) {

	if (!newwindow.closed && newwindow.location) {
		newwindow.location.href = url;
	}
	else {
		newwindow = window.open(url,name,props);
		if (!newwindow.opener) newwindow.opener = self;
	}
	if (window.focus) {newwindow.focus()}
	return false;
}

function getPairs( min ) {

	var picklist = document.practicef.picklist.options;
	
	if ( picklist.length < min ) {
		alert("There must be at least " + min + " entries in the Practice Set.");
		return null;
	}
	
	var pairs = [];
	var i = 0;
	while( pairs.length < picklist.length ) {
		var idx = getRandomIndex( picklist.length );
		if ( pairs.indexOf( picklist[idx].value ) == -1 ) {
			pairs[i++] = picklist[idx].value;
		}
	}
	return pairs;
}

function getRandomIndex( val ) {
	return Math.floor(Math.random() * val);
}

function getRandomIndices(max) {

	var indices = [];
	var i = 0;
	var j = 0;
	while ( indices.length < max && j < 30) {
		var idx = getRandomIndex( max );
		if ( indices.indexOf( idx ) == -1 ) {
			indices[i++] = idx;
		}
	}
	return indices;
}

function getCheckedValue(radioObj) {
	if(!radioObj) {
		return "";
	}
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		if(radioObj.checked) {
			return radioObj.value;
		} else {
			return "";
		}
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		
		}
	}
	return "";
}

function getMatch(value,id) {

	var pairs = value.split(";");
	for( i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split(",");
		if ( pair[0] == id ) {
			return pair[1];
		} else if ( pair[1] == id ) {
			return pair[0];
		}
	}
	return null;
}

function setMatch(matches,id1,id2) {

	if ( matches.value != "" ) {
		matches.value += ";";
	}
	matches.value += (id1 + "," + id2);
}

///////// FLASHCARDS /////////

function showCards() {
	var language = document.practicef.language.value;
	document.cardsf.showcards[1].value = language;
	document.getElementById("cardtype_span").innerHTML = language;
	document.practicef.picklist.options.length = 0;
	document.practicef.listid.value = "1";
	document.practicef.morebutton.disabled=false;
	document.cardsf.showcards[0].checked = true;
	switchLayoutOther();
	removeAllItems(document.practicef.pool);
	removeAllItems(document.practicef.picklist);
}

function shuffle() {
	
	var picklist = document.practicef.picklist.options;
	if ( picklist.length == 0 ) {
		alert("There must be at least 1 entry in the Practice Set.");
		return;
	}
	document.cardsf.currentcard.value = "0";
	var indices = getRandomIndices(picklist.length);
	var cardorder = "";
	for ( var i = 0; i < indices.length; i++ ) {
		cardorder += indices[i];
		if ( i < indices.length - 1 ) {
			cardorder += ",";
		}
	}
	document.cardsf.cardorder.value = cardorder;
	nextCard();
}

function checkAnswer() {

	var answer = document.cardsf.word2.value;
	var entry = document.cardsf.entry.value;
	if ( answer == entry ) {
		showAnswer();
	} else {
		document.getElementById("InnerCardDisp").innerHTML = document.cardsf.word1.value + "<br><span style=\"color: #800;font-size:medium\">" + 
			"Try again!</span>";
	}
}

function showAnswer() {
	
	document.getElementById("InnerCardDisp").innerHTML = document.cardsf.word1.value + "<br><span style=\"color: #800;font-size:medium\">" + 
		document.cardsf.word2.value + "</span>";	
}

function nextCard() {
	
	var picklist = document.practicef.picklist.options;
	var split = document.cardsf.cardorder.value.split(",");
	var i = parseInt( document.cardsf.currentcard.value );
	if ( i == split.length-1 ) i = 0;
	else i++;
	document.cardsf.currentcard.value = "" + (i);
	var pick = parseInt( split[i] );
	var pair = picklist[pick].value.split(",");
	var cardval = "";
	var showcardval = getCheckedValue( document.cardsf.showcards );
	if ( showcardval == "English" ) {
		cardval = "<a href=\"javascript:void(0)\" class=\"flashcard\" title=\"" + pair[2] + "\">" + pair[0] + "</a>";
		document.cardsf.word1.value = pair[0];
		document.cardsf.word2.value = pair[1];
	} else {
		cardval = pair[1];
		document.cardsf.word1.value = pair[1];
		document.cardsf.word2.value = pair[0];
	}
	document.getElementById("InnerCardDisp").innerHTML = cardval;
}

//////// MEMORY GAME ////////

function showGame() {
	
	var top = 35;
	var id = 0;
	for ( r = 0; r < 4 ; r++ ) {
		var left = 10;
		for ( c = 0; c < 4; c++ ) {
			style = "cursor: pointer;left:" + left + "px;top:" + top + "px;" +
					"position:absolute;width:100px;height:100px;border:1px solid #000;";
			topStyle = style + "background-color:#FDD017;z-index:1";
			bottomStyle = style + "background-color:#FFF;display:table-cell;text-align:center";
			document.write("<div id=\"top_" + id + "\" style=\"" + topStyle + "\" onclick=\"showBottom('" + id + "')\"></div>");
			document.write("<div id=\"bottom_" + id + "\" style=\"" + bottomStyle + "\"></div>");
			left += 101;
			id++;
		}
		top += 101;
	}
}

function hideTop(id,vis) {
	setVisibility("top_" + id,vis);
}

function showBottom(id) {

	hideTop(id,"hidden");
 		
	if ( document.gamef.pick.value != "" &&
		 document.gamef.pick.value != getMatch(	document.gamef.matches.value, id ) ) {
		setTimeout("hideTop('" + document.gamef.pick.value + "','visible')",1000);
		setTimeout("hideTop('" + id + "','visible')",1000);
	} 

	if ( document.gamef.pick.value == "" ) {
		document.gamef.pick.value = id;
	} else {
		document.gamef.pick.value = "";
	}
}

function fillGame() {

	resetGame();
	
	var pairs = getPairs(8);
	if ( pairs == null ) return;
	var indices = getRandomIndices(16);
	var cells = []; 
	var j = 0;
	for ( var i = 0; i < 8; i++ ) {
		var pair = pairs[i].split(",");
		var idx1 = indices[j++];
		var idx2 = indices[j++];
		fillCell(cells,pair[0],idx1);
		fillCell(cells,pair[1],idx2);
		setMatch(document.gamef.matches,idx1,idx2);
	}
}

function resetGame() {
	
	document.gamef.pick.value = "";
	document.gamef.matches.value = "";
	for ( i = 0; i < 16; i++ ) {
		hideTop(i,"visible");
	}
}

function hideGame() {

	for ( i = 0; i < 16; i++ ) {
		hideTop(i,"hidden");
	}
}

function fillCell(cells,val,idx) {

	cells[idx] = val;
	document.getElementById('bottom_' + idx).innerHTML = val;
}

function setVisibility(id,vis) {
	document.getElementById(id).style.visibility = vis;
}

//////// MATCH GAME ////////

function showMatching() {

	var top = 35;
	for ( r = 0; r < 10 ; r++ ) {
		var left = 10;
		for ( c = 0; c < 2; c++ ) {
			style = "cursor: pointer;left:" + left + "px;top:" + top + "px;" +
					"position:absolute;width:175px;height:35px;border:1px solid #000;" +
					"background-color:#FDD017;text-align:center";
			var match = (c==0) ? "match_" + r + "L" : "match_" + r + "R";
			var mouse = (c==0) ? "mouseDownL('" + match + "')" : "mouseDownR('" + match + "')";
			document.write("<div id=\"" + match + "\" style=\"" + style + "\" onmousedown=\"" + mouse + "\"></div>");
			left += 310;
		}
		top += 42;
	}		
}

function fillMatching() {
		
	resetMatching();
	
	var pairs = getPairs(10);
	if ( pairs == null ) return;
	var indicesL = getRandomIndices(10);
	var indicesR = getRandomIndices(10);
	var showmatch = getCheckedValue( document.matchf.showmatch );
	for ( r = 0; r < 10; r++ ) {
		var pair = pairs[r].split(",");
		var idxL = indicesL[r];
		var idxR = indicesR[r];
		if ( showmatch == "English" ) {			
			fillWordL( idxL, pair[0] );
			fillWordR( idxR, pair[1] );
		} else {
			fillWordL( idxL, pair[1] );
			fillWordR( idxR, pair[0] );		
		}
		setMatch(document.matchf.matches,
			"match_" + idxL + "L","match_" + idxR + "R");
	}
}

function resetMatching() {
	
	if ( !canvas ) {
		canvas = new jsGraphics("Content2");
		canvas.setStroke(2);
	}
	canvas.clear();
	document.matchf.leftId.value = "";
	document.matchf.pairings.value = "";	
	document.matchf.matches.value = "";
	for ( r = 0; r < 10; r++ ) {
		fillWordL( r, "" ); 
		fillWordR( r, "" );		
	}
}

function fillWordL( id, val ) {
	fillWord( id + "L", val );
}

function fillWordR( id, val ) {
	fillWord( id + "R", val );
}

function fillWord( id, val ) {
	document.getElementById("match_" + id).innerHTML = val;
}

function addPairing(idL, idR) {
	
	var pairings = document.matchf.pairings.value;
	if ( pairings ) {
		pairings += ";";
	}
	pairings += idL + "," + idR;
	document.matchf.pairings.value = pairings; 
}

function removePairing(id) {
	
	var pairings = document.matchf.pairings.value;
	if ( !pairings ) return;
	var first = pairings.indexOf(id + ",");
	if ( first >= 0 ) {
		var second = pairings.indexOf(";",first);
		var before = (first > 0)?pairings.substring(0,first-1):"";
		var after = (second >= 0)?pairings.substring(second+1):"";
		document.matchf.pairings.value = before + 
					((before != "" && after != "")?";":"") + after;
	}
}

function redrawPairings(highlight) {

	canvas.clear();
	var pairings = document.matchf.pairings.value;
	var matches = document.matchf.matches.value;
	if ( !pairings ) return;
	var pairs = pairings.split(";");
	var matchList = [];
	if ( highlight ) {
		for ( i = 0; i < pairs.length; i++ ) {
			var pair = pairs[i].split(",");
			var idx1 = matches.indexOf( pair[0] );
			var idx2 = matches.indexOf( ",", idx1 );
			var idx3 = matches.indexOf( ";", idx2 );
			if ( idx3 == -1 ) idx3 = matches.length;
			matchList[i] = matches.substring( idx2 + 1, idx3 );
		}
	}
	for( i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split(",");
		if ( highlight ) {
			if ( matchList[i] != pair[1] ) canvas.setColor("#800000");
			else canvas.setColor("#C0C0C0");
		} else {
			canvas.setColor("#000");
		}
		var leftMatch = document.getElementById( pair[0] );
		var rightMatch = document.getElementById( pair[1] );
		canvas.drawLine(leftMatch.offsetLeft + leftMatch.offsetWidth, 
						leftMatch.offsetTop + leftMatch.offsetHeight/2,
						rightMatch.offsetLeft-1,
						rightMatch.offsetTop + rightMatch.offsetHeight/2);	
	}
	canvas.paint();
}

function mouseDownL(id) {
	
	removePairing(id);
	redrawPairings(false);
	document.matchf.leftId.value = id;
	document.getElementById("Content2").onmousemove = mouseMove;
}

function mouseDownR(id) {
	
	if ( document.matchf.leftId.value == "" ) return;
	document.getElementById("Content2").onmousemove = null;
	addPairing(document.matchf.leftId.value,id);
	redrawPairings(false);
	document.matchf.leftId.value = "";	
}

function mouseMove(e) {
	
	// optimized for Firefox 3.0 and IE 7
	redrawPairings(false);
	var leftMatch = document.getElementById(document.matchf.leftId.value);
	var pos = findPagePos(leftMatch.offsetParent);
	var coords = findCoords(e);
	var adjX = isIE()?-6:-6;
	var adjY = isIE()?160:-5;
	var x = coords[0] - pos[0] + adjX;
	var y = coords[1] - pos[1] + adjY;
	canvas.setColor("#C0C0C0");
	canvas.drawLine(leftMatch.offsetLeft + leftMatch.offsetWidth, 
					leftMatch.offsetTop + leftMatch.offsetHeight/2,
					x,y);
	canvas.paint();	
}

function debug(m) {

	var debug = document.getElementById("debug");
	debug.innerHTML += m + "<br>";
}